package com.veal98.tree;

import com.veal98.bean.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class BinaryTreePostorderTraversal_145 {

    // 递归
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();

        if (root == null) {
            return res;
        }

        res.add(root.val);
        postorderTraversal(root.left);
        postorderTraversal(root.right);

        return res;
    }

    // 迭代
    public List<Integer> postorderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<>();

        if (root == null) {
            return res;
        }

        // 辅助栈
        Stack<TreeNode> stack = new Stack<>();
        // 工作指针
        TreeNode cur = root;
        // 最近访问过的节点
        TreeNode visited = null;

        while (!stack.isEmpty() || cur != null) {
            if (cur != null) {
                stack.push(cur);
                // 左
                cur = cur.left;
            } else {
                cur = stack.peek();
                // 右
                if (cur.right != null && cur.right != visited) {
                    cur = cur.right;
                    stack.push(cur);
                    // 再走到最左
                    cur = cur.left;
                } else {
                    cur = stack.pop();
                    // 根
                    res.add(cur.val);

                    // 更新最近访问过的节点
                    visited = cur;

                    cur = null;
                }
            }
        }

        return res;
    }
}
